package com.orangelife.mobile.individual.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.common.sp.UserSp;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.StringUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.app.application.CurryApplication;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.main.activity.MainTablActivity;
import com.orangelife.mobile.util.CryptoDES;
import com.orangelife.mobile.verify.biz.SmsHttpBiz;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 修改手机号
 *
 * @author lxj
 */
public class ChangePhoneNumActivity extends OrangeLifeBaseActivity {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.etPhoneNum)
    EditText etPhoneNum;
    @Bind(R.id.et_code)
    EditText etCode;
    @Bind(R.id.tvGetCode)
    TextView tvGetCode;
    @Bind(R.id.btn_submit)
    Button btnSubmit;
    private int timeSendSms = 59;
    private Timer timer;
    public static final String TAG = "ChangePhoneNumActivity";
    private Dialog dialog;
    String strValidateCode = "";
    ChangePhoneNumHandler handler;

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        CurryApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_change_phone_number);
        ButterKnife.bind(this);
        initView();
        findView();
    }

    public void hideInput(View v) {
        InputMethodManager imm = (InputMethodManager) this
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    private void initView() {
        handler = new ChangePhoneNumHandler(this);
    }

    private void findView() {
        tvTitle.setText("修改绑定手机号");
        tvGetCode.setOnClickListener(clickListener);
        btnSubmit.setOnClickListener(clickListener);
    }

    public void onBackClick(View v) {
        Intent data = getIntent();
        Intent intent = new Intent();
        CurryApplication.getInstance().setUpdate(false);
        if ("register".equals(data.getStringExtra("register"))) {
            intent.setClass(ChangePhoneNumActivity.this,
                    MainTablActivity.class);
            startActivity(intent);
        } else {
            finish();
        }
    }


    /**
     * 监听器——根据id判断并执行相应操作
     */
    OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tvGetCode:
                    String phone = etPhoneNum.getText().toString();
                    if (StringUtil.isContainBlank(phone)) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources()
                                        .getString(R.string.phone_number_null));
                    } else if (phone.length() != 11) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.register_phone_error));
                    } else if (UserSp.getRegPhone().equals(phone)) {
                        ToastHelper.getInstance().displayToastWithQuickClose("您输入的新手机号与当前绑定的相同，请重新输入");
                    } else {
                        if (isConnected()) {
                            dialog = DialogHelper
                                    .getInstance()
                                    .createLoadingDialog(
                                            ChangePhoneNumActivity.this,
                                            getResources()
                                                    .getString(
                                                            R.string.register_request_vercode));
                            dialog.show();
                            SmsHttpBiz.getSmsCode(phone, "6", handler, 0);
                            countDownSendSmsAgain();
                        }
                    }
                    break;
                case R.id.btn_submit:
                    String phone1 = etPhoneNum.getText().toString();
                    String code = String.valueOf(etCode.getText());
                    if (StringUtil.isContainBlank(phone1)) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources()
                                        .getString(R.string.phone_number_null));
                    } else if (phone1.length() != 11) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.register_phone_error));
                    } else if (StringUtil.isContainBlank(code)) {
                        ToastHelper.getInstance().displayToastWithQuickClose(
                                getResources().getString(
                                        R.string.verification_code_null));
                    } else {
                        if (!isConnected()) {
                            return;
                        }
                        dialog = DialogHelper.getInstance().createLoadingDialog(
                                ChangePhoneNumActivity.this,
                                getResources().getString(
                                        R.string.register_user_info));
                        dialog.show();

                        try {
                            phone1 = CryptoDES.encrypt(phone1, Constant.DES_KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        sendRequestForChangePhone(phone1, code);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 用户修改手机号请求
     *
     * @param phone1 电话
     * @param code   验证码
     */
    private void sendRequestForChangePhone(String phone1, String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("memberName", phone1);
        map.put("verifyCode", code);
        VolleyHttpUtil.getInstance().putWithHandler(Constant.URL_CHANGEPHONE, map, handler, 1, null);
    }

    /**
     * 重置验证码时间
     */
    private void countDownSendSmsAgain() {
        /* 点击发送验证码后进行倒计时 */
        timeSendSms = 59;
        tvGetCode.setEnabled(false);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.obtainMessage(Constant.WHAT_COUNT_DOWN, timeSendSms--)
                        .sendToTarget();
            }
        }, 0, 1000);
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.WHAT_COUNT_DOWN:
                    if (timeSendSms >= 0 && !("stop".equals(strValidateCode))) {
                        tvGetCode.setText(getResources().getString(R.string.wait)
                                + timeSendSms
                                + getResources().getString(R.string.seconds));
                    } else {
                        tvGetCode.setEnabled(true);
                        tvGetCode.setText(getResources().getString(
                                R.string.send_again));
                        timer.cancel();
                    }
                    break;
                default:
                    break;
            }
        }

    };

    /**
     * 接收处理线程返回的消息
     */
    static class ChangePhoneNumHandler extends Handler {
        private WeakReference<ChangePhoneNumActivity> changePhoneNumActivity = null;

        public ChangePhoneNumHandler(ChangePhoneNumActivity activity) {
            changePhoneNumActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            ChangePhoneNumActivity act = changePhoneNumActivity.get();

            if (act != null) {
                switch (msg.what) {
                    case 500:
                        DialogHelper.closeDialog(act.dialog);
                        HashMap<String, Object> map2 = (HashMap<String, Object>) JSONHelper
                                .jsonToMap(String.valueOf(msg.obj));
                        if (map2 != null) {
                            String errInfo2 = String.valueOf(map2
                                    .get(Constant.RESULT_MESSAGE_KEY));
                            ToastHelper.getInstance().displayToastWithQuickClose(
                                    errInfo2);
                        } else {
                            ToastHelper.getInstance().displayToastWithQuickClose(
                                    msg.obj.toString());
                        }
                        break;
                    case Constant.WHAT_COUNT_DOWN:
                        if (act.timeSendSms >= 0) {
                            act.tvGetCode.setText(act.getResources()
                                    .getString(R.string.wait)
                                    + act.timeSendSms
                                    + act.getResources().getString(R.string.seconds));

                        } else {
                            act.tvGetCode.setEnabled(true);
                            act.tvGetCode.setText(act.getResources().getString(
                                    R.string.send_again));
                            act.timer.cancel();
                        }
                        break;
                    case 0:
                        if (msg.obj != null) {
                            HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                                    .jsonToMap(String.valueOf(msg.obj));
                            if (map != null) {
                                int errCode = Integer.parseInt(map.get(
                                        Constant.RESULT_KEY).toString());
                                String errInfo = String.valueOf(map
                                        .get(Constant.RESULT_MESSAGE_KEY));
                                Log.e(TAG, "" + msg.what);
                                if (errCode == Constant.RESULT_SUCCESS) {
                                    ToastHelper.getInstance()
                                            .displayToastWithQuickClose(
                                                    act.getResources().getString(
                                                            R.string.send_sms_success));
                                } else {
                                    ToastHelper.getInstance()
                                            .displayToastWithQuickClose(errInfo);
                                    act.timeSendSms = 0;
                                }
                            }
                        } else {
                            ToastHelper.getInstance().displayToastWithQuickClose(
                                    act.getResources().getString(R.string.send_sms_fail));
                            act.timeSendSms = 0;
                        }
                        break;
                    case 1:
                        if (msg.obj != null) {
                            HashMap<String, Object> map = (HashMap<String, Object>) JSONHelper
                                    .jsonToMap(String.valueOf(msg.obj));
                            if (map != null) {
                                int errCode = Integer.parseInt(map.get(
                                        Constant.RESULT_KEY).toString());
                                String errInfo = String.valueOf(map
                                        .get(Constant.RESULT_MESSAGE_KEY));
                                Log.e(TAG, "" + msg.what);
                                if (errCode == Constant.RESULT_SUCCESS) {
                                    ToastHelper.getInstance()
                                            .displayToastWithQuickClose(
                                                    act.getResources().getString(
                                                            R.string.modify_success));
                                    HashMap<String, Object> map1 = (HashMap<String, Object>) map
                                            .get("entity");
                                    UserSp.setRegPhone(String.valueOf(map1.get("phone")));
                                    act.finish();
                                } else {
                                    ToastHelper.getInstance()
                                            .displayToastWithQuickClose(errInfo);
                                }

                            } else {
                                ToastHelper.getInstance()
                                        .displayToastWithQuickClose(
                                                act.getResources().getString(
                                                        R.string.modify_faild));
                            }
                        }
                        break;
                }

                if (act.dialog != null) {
                    act.dialog.dismiss();
                }
            }
        }
    }
}
